<template>
  <t-dialog
    :visible="visible"
    width="60%"
    :header="title"
    :close-on-overlay-click="false"
    :footer="false"
    @update:visible="(val) => emit('update:visible', val)"
  >
    <t-tabs :default-value="activeTab">
      <t-tab-panel value="material" label="原料管理">
        <t-space direction="vertical" style="width: 100%">
          <t-button theme="primary" @click="addMaterial">添加原料</t-button>
          <t-table :data="materialList" :columns="materialColumns" :bordered="true" :stripe="true" row-key="id" />
        </t-space>
      </t-tab-panel>
      <t-tab-panel value="steps" label="步骤管理">
        <t-space direction="vertical" style="width: 100%">
          <t-button theme="primary" @click="addStep">添加步骤</t-button>
          <t-table
            :data="stepsList"
            :columns="stepsColumns"
            :bordered="true"
            :stripe="true"
            row-key="id"
            drag-sort="row-handler"
            @drag-sort="onStepDragSort"
          />
        </t-space>
      </t-tab-panel>
    </t-tabs>
  </t-dialog>

  <!-- 添加/编辑原料弹窗 -->
  <t-dialog
    v-model:visible="showMaterialDialog"
    :header="materialDialogTitle"
    width="500px"
    :confirm-btn="{ content: '确定', theme: 'primary' }"
    :cancel-btn="{ content: '取消', theme: 'default' }"
    @confirm="onMaterialSubmit"
  >
    <t-form ref="materialFormRef" :data="materialForm" :rules="materialRules">
      <t-form-item label="药材名称" name="materialId">
        <t-select
          v-model="materialForm.materialId"
          :options="materialOptions"
          placeholder="请选择药材"
          clearable
          filterable
        />
      </t-form-item>
      <t-form-item label="用量" name="dosage">
        <t-input v-model="materialForm.dosage" placeholder="请输入用量" />
      </t-form-item>
    </t-form>
  </t-dialog>

  <!-- 添加/编辑步骤弹窗 -->
  <t-dialog
    v-model:visible="showStepDialog"
    :header="stepDialogTitle"
    width="500px"
    :confirm-btn="{ content: '确定', theme: 'primary' }"
    :cancel-btn="{ content: '取消', theme: 'default' }"
    @confirm="onStepSubmit"
  >
    <t-form ref="stepFormRef" :data="stepForm" :rules="stepRules">
      <t-form-item label="步骤描述" name="description">
        <t-textarea v-model="stepForm.description" placeholder="请输入步骤描述" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script setup lang="ts">
import type { FormInstanceFunctions } from 'tdesign-vue-next';
import { DialogPlugin, Icon, Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import { addMaterialsApi, addStepsApi, deleteMaterialsApi, sortStepsApi } from '@/api/dishes';
import { getAllMaterialsApi } from '@/api/medicinal';

defineOptions({
  name: 'StepsDialog',
});

const props = defineProps<{
  visible: boolean;
  title: string;
  materialList: any[];
  stepsList: any[];
  dishId: number;
}>();

const emit = defineEmits(['update:visible', 'update:materialList', 'update:stepsList']);

// 当前激活的标签
const activeTab = ref('material');

// 原料相关
const showMaterialDialog = ref(false);
const materialDialogTitle = ref('添加原料');
const materialForm = ref({
  dishId: props.dishId,
  materialId: null,
  materialName: '',
  dosage: '',
});
const materialFormRef = ref<FormInstanceFunctions>();
const materialRules = {
  materialId: [{ required: true, message: '请选择药材' }],
  dosage: [{ required: true, message: '请输入用量' }],
};
const materialOptions = ref([]);

// 获取所有药材选项
onMounted(async () => {
  const materials = await getAllMaterialsApi();
  materialOptions.value = materials.map((material: { label: string; value: string }) => {
    return {
      label: material.label,
      value: Number(material.value),
    };
  });
});

// 原料表格列配置
const materialColumns = [
  { colKey: 'materialName', title: '药材名称', width: '200' },
  { colKey: 'dosage', title: '用量', width: '200' },
  {
    colKey: 'operation',
    title: '操作',
    width: '160',
    cell: (h: Function, { row }: any) => {
      return h(Space, {}, () => [
        h(
          Link,
          {
            theme: 'primary',
            underline: false,
            onClick: () => editMaterial(row),
          },
          () => '编辑',
        ),
        h(
          Link,
          {
            theme: 'danger',
            underline: false,
            onClick: () => deleteMaterial(row),
          },
          () => '删除',
        ),
      ]);
    },
  },
];

// 步骤相关
const showStepDialog = ref(false);
const stepDialogTitle = ref('添加步骤');
const stepForm = ref({
  id: null,
  description: '',
  stepNumber: 0,
});
const stepFormRef = ref<FormInstanceFunctions>();
const stepRules = {
  description: [{ required: true, message: '请输入步骤描述' }],
};

// 步骤表格列配置
const stepsColumns = [
  {
    colKey: 'drag', // 列拖拽排序必要参数
    title: '排序',
    cell: (h: any) => h(Icon, { name: 'move' }, {}),
    width: 46,
  },
  { colKey: 'stepNumber', title: '步骤序号', width: '100' },
  { colKey: 'description', title: '步骤描述' },
  {
    colKey: 'operation',
    title: '操作',
    width: '160',
    cell: (h: Function, { row }: any) => {
      return h(Space, {}, () => [
        h(
          Link,
          {
            theme: 'primary',
            underline: false,
            onClick: () => editStep(row),
          },
          () => '编辑',
        ),
        h(
          Link,
          {
            theme: 'danger',
            underline: false,
            onClick: () => deleteStep(row),
          },
          () => '删除',
        ),
      ]);
    },
  },
];

// 原料相关方法
const addMaterial = () => {
  materialForm.value = {
    dishId: props.dishId,
    materialId: null,
    materialName: '',
    dosage: '',
  };
  materialDialogTitle.value = '添加原料';
  showMaterialDialog.value = true;
};

const editMaterial = (row: any) => {
  materialForm.value = { ...row };
  materialForm.value.dishId = props.dishId;
  materialDialogTitle.value = '编辑原料';
  showMaterialDialog.value = true;
};

const deleteMaterial = (row: any) => {
  const confirm = DialogPlugin.confirm({
    header: '提示',
    body: '确定要删除该原料吗？',
    onConfirm: async () => {
      const newList = props.materialList.filter((item) => item.materialId !== row.materialId);
      emit('update:materialList', newList);
      await deleteMaterialsApi(props.dishId, row.materialId);
      MessagePlugin.success('删除成功');
      confirm.hide();
    },
  });
};

const onMaterialSubmit = async () => {
  const valid = await materialFormRef.value?.validate();
  if (valid === true) {
    // 修改列表更新逻辑
    let newList = [...props.materialList];
    if (materialForm.value.materialName) {
      // 编辑时替换原有数据
      const index = newList.findIndex((item) => item.materialName === materialForm.value.materialName);
      const material = materialOptions.value.find((item: any) => item.value === materialForm.value.materialId);
      materialForm.value.materialName = material?.label;
      if (index > -1) {
        newList[index] = materialForm.value;
      }
    } else {
      const material = materialOptions.value.find((item: any) => item.value === materialForm.value.materialId);
      materialForm.value.materialName = material?.label;
      newList = newList.concat(materialForm.value);
    }
    emit('update:materialList', newList);
    const params = {
      dishId: props.dishId,
      dosage: newList.map((item) => {
        return {
          materialId: item.materialId,
          dosage: item.dosage,
        };
      }),
    };
    await addMaterialsApi(params);
    showMaterialDialog.value = false;
    MessagePlugin.success('操作成功');
  }
};

// 步骤相关方法
const addStep = () => {
  stepForm.value = {
    id: null,
    description: '',
    stepNumber: props.stepsList.length + 1,
  };
  stepDialogTitle.value = '添加步骤';
  showStepDialog.value = true;
};

const editStep = (row: any) => {
  stepForm.value = { ...row };
  stepDialogTitle.value = '编辑步骤';
  showStepDialog.value = true;
};

const deleteStep = (row: any) => {
  const confirm = DialogPlugin.confirm({
    header: '提示',
    body: '确定要删除该步骤吗？',
    onConfirm: async () => {
      let newList = props.stepsList.filter((item) => item.id !== row.id);
      // 重新计算步骤序号
      newList = newList.map((item, index) => ({
        ...item,
        stepNumber: index + 1,
        dishId: props.dishId,
      }));
      await sortStepsApi(newList);
      emit('update:stepsList', newList);
      MessagePlugin.success('删除成功');
      confirm.hide();
    },
  });
};

const onStepSubmit = async () => {
  const valid = await stepFormRef.value?.validate();
  if (valid === true) {
    let newList = [...props.stepsList];
    if (stepForm.value.id) {
      // 编辑
      newList = newList.map((item) => (item.id === stepForm.value.id ? stepForm.value : item));
    } else {
      // 新增
      stepForm.value.stepNumber = newList.length + 1;
      newList.push(stepForm.value);
    }
    emit('update:stepsList', newList);
    const params = {
      dishId: props.dishId,
      id: stepForm.value.id || null,
      description: stepForm.value.description,
      stepNumber: stepForm.value.stepNumber,
    };
    await addStepsApi(params);
    showStepDialog.value = false;
    MessagePlugin.success('操作成功');
  }
};

// 步骤拖拽排序
const onStepDragSort = async ({ currentIndex, targetIndex }: any) => {
  const steps = [...props.stepsList];
  const [removed] = steps.splice(currentIndex, 1);
  steps.splice(targetIndex, 0, removed);
  // 重新计算步骤序号
  const newList = steps.map((item, index) => ({
    ...item,
    stepNumber: index + 1,
    dishId: props.dishId,
  }));
  await sortStepsApi(newList);
  emit('update:stepsList', newList);
};
</script>

<style lang="less" scoped>
:deep(.t-tabs__content) {
  padding: 16px 0;
}

:deep(.t-table) {
  margin-top: 16px;

  .t-table__row-drag-handler {
    cursor: move;
  }
}
</style>
